package com.yang.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yang.common.PageQuery;
import com.yang.entity.dto.UserDTO;
import com.yang.entity.vo.UserVO;
import com.yang.mapper.UserMapper;
import com.yang.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 新增用户信息
     * @param userDTO
     * @return
     */
    @Override
    public int add(UserDTO userDTO) {
        String id = UUID.randomUUID().toString().replace("-", "");
        log.info("生成的人员id为: {}", id);
        userDTO.setId(id);
        int insert = userMapper.insert(userDTO);
        if (insert == 1) {
            log.info("新增人员信息成功");
        } else {
            log.error("新增人员信息失败");
        }
        return insert;
    }

    /**
     * 分页查询用户信息
     * @param pageQuery
     * @return
     */
    @Override
    public PageInfo<UserVO> pageQuery(PageQuery<UserDTO> pageQuery) {
        UserDTO params = pageQuery.getParams();
        PageHelper.startPage(pageQuery.getPageNum(), pageQuery.getPageSize());
        List<UserVO> list = userMapper.list(params);
        if (CollectionUtils.isNotEmpty(list)) {
            return new PageInfo<>(list);
        }
        return new PageInfo<>(Collections.emptyList());
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @Override
    public UserVO getUserById(String id) {
        UserVO result = userMapper.getUserById(id);
        return result;
    }

    /**
     * 修改用户信息
     * @param userDTO
     * @return
     */
    @Override
    public int update(UserDTO userDTO) {
        int result = userMapper.update(userDTO);
        return result;
    }

    /**
     * 删除用户信息
     * @param userDTO
     * @return
     */
    @Override
    public int remove(UserDTO userDTO) {
        // 设置删除标志为已删除
        userDTO.setIsDeleted(1);
        if (StringUtils.isNotEmpty(userDTO.getId())) {
            int update = userMapper.update(userDTO);
            if (update == 1) {
                log.info("删除用户成功");
                return update;
            } else {
                log.error("删除用户失败");
                return 0;
            }
        } else if (CollectionUtils.isNotEmpty(userDTO.getIdList())) {
            int update = userMapper.update(userDTO);
            if (update == userDTO.getIdList().size()) {
                log.info("批量删除用户成功");
                return update;
            } else {
                log.error("批量删除用户失败");
                return 0;
            }
        }
        log.error("未接收到待删除的用户id");
        return 0;
    }

}
